import {clearInterval} from "timers";

export default function useClock (){
    const clock=reactive({
        date:'',
        time:'',
    })
    const timerID = ref<any>(null)
    function updateTime() {
        let cd = new Date();
        clock.time = zeroPadding(cd.getHours(), 2) + ':' + zeroPadding(cd.getMinutes(), 2) + ':' + zeroPadding(cd.getSeconds(), 2);
        clock.date = cd.getFullYear() + '年' + (cd.getMonth() + 1) + '月' + cd.getDate()+'日'
    }

    function zeroPadding(num:number, digit:number) {
        let zero = '';
        for (let i = 0; i < digit; ++i) {
            zero += '0';
        }
        return (zero + num).slice(-digit);
    }
    onMounted(()=>{
        if(timerID.value)window.clearInterval(timerID.value)
        timerID.value = setInterval(updateTime, 1000);
        updateTime();
    })
    onUnmounted(()=>{
        window.clearInterval(timerID.value)
        timerID.value=null
    })
    return {
        clock
    }
}